#include <iostream>
#include <mysql/mysql.h>
#include <string>

// 1. 初始化mysql：mysql_init
// 2. 连接mysql：mysql_real_connect
// 3. 发送mysql命令：mysql_query
// 4. 获取执行结果：mysql_store_result
//      4.1 获取结果行数：mysql_num_rows
//      4.2 获取结果列数：mysql_num_fields
//      4.3 获取结果内容：mysql_fetch_row
// 5. 关闭mysql连接：mysql_close

const std::string sql_host = "localhost";
const std::string sql_user = "zs";
const std::string sql_passwd = "Zs20030323#";
const std::string sql_db = "db1";
unsigned int port = 8080;
int main()
{
    // std::cout << "mysql client version: " << mysql_get_client_info() << std::endl;

    MYSQL my;
    if(mysql_init(&my) == nullptr)
    {
        fprintf(stderr, "mysql_init() failed\n");
        exit(0);
    }

    if(!mysql_real_connect(&my,sql_host.c_str(),sql_user.c_str(),sql_passwd.c_str(),sql_db.c_str(),
                        port,nullptr,0))
    {
        fprintf(stderr, "mysql_real_connect() failed: %s\n", mysql_error(&my));
        exit(0);
    }

    // const std::string sql = "Create table test_vs(id int,name varchar(20))";
    // const std::string sql = "insert into test_vs values(2,'罗峰')";
    // const std::string sql = "delete from test_vs where id=2";
    // const std::string sql = "update test_vs set name='222' where name='111'";
    const std::string sql = "select * from dept_manager";
    if(mysql_query(&my,sql.c_str()) != 0)
    {
        fprintf(stderr, "mysql_query() failed: %s\n", mysql_error(&my));
        exit(0);
    }

    MYSQL_RES* res = mysql_store_result(&my);
    unsigned int fields = mysql_num_fields(res);
    MYSQL_FIELD *field_name = mysql_fetch_fields(res);
    for(int i = 0;i < fields;i++)
    {
        std::cout << field_name[i].name << "\t";
    }
    std::cout << std::endl;

    my_ulonglong rows = mysql_num_rows(res);
    MYSQL_ROW line;
    for(int i = 0;i < rows;i++)
    {
        line = mysql_fetch_row(res);
        int j = 0;
        for(int j = 0;j < fields;j++)
            std::cout << line[j] << "\t";

        std::cout << std::endl;
    }
    
    mysql_close(&my);

    return 0;
}